package cn.itcast.servlet;

import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import cn.itcast.service.impl.UserserviceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private UserService service  = new UserserviceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置字符编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String method = req.getParameter("method");

        if ("login".equals(method)){
            login(req,resp);
        }else if("findAll".equals(method)){
            findAll(req,resp);
        }

    }
    //登录验证
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取页面数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //System.out.println(username +"=="+ password);

        //调用service方法
        User user =   service.login(username,password);
        if (user!=null){//登录验证成功

            req.getRequestDispatcher("/user?method=findAll").forward(req,resp);
            System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!");
        }else{
            resp.getWriter().write("登录失败");
            System.out.println("登录失败");
        }
    }
    //查询所有
    protected void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

       List<User> list =  service.findAll();
       req.setAttribute("list",list);
       req.getRequestDispatcher("/main.jsp").forward(req,resp);
    }

}
